package com.hsc.www.rawTest.事务;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ConfirmSend31 {
    /**
     * 队列名
     */
    private static final String QUEUE_NAME = "test_queue_confirm1";
    /**
     * exchange
     */
    private static final String EXCHANGE_NAME = "test_queue_exchange";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setHost("172.172.172.11");
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPort(5672);
        // 获取 connection
        Connection connection = connectionFactory.newConnection();
        // 从连接开两个通道
        Channel channel = connection.createChannel();

        channel.queueDeclare("testQueue", false, false, false, null);
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("-------ack!-----------deliveryTag=" + deliveryTag + "  multiple=" + multiple);
            }
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("-------no ack!-----------deliveryTag=" + deliveryTag + "  multiple=" + multiple);
            }
        });

        channel.basicPublish("", "testQueue", true, null, "你好".getBytes());

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String message = new String(body, StandardCharsets.UTF_8);
                System.out.println(message);
            }
        };
        channel.basicConsume("testQueue", true, consumer);
        Thread.sleep(600 * 1000);
        channel.close();
        connection.close();

    }
}
